package com.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.feng.entity.User;
import com.feng.service.IUserConfigService;
import com.feng.util.CommonUtils;
import com.feng.util.CookieUtils;
import com.feng.util.Dict;
import com.feng.util.RedisUtils;

public class URLInterceptor implements HandlerInterceptor {

	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	private IUserConfigService userConfigService;
	
	@Value("${userSession.timout}")
	private long timout;
	
	//redis开关
	@Value("${mblog.redis.enabled}")
	private Boolean redisIsEnabled;
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		String url=request.getRequestURL().toString();
		System.out.println(url);
		if(url.endsWith("userLogin") || url.endsWith("error") || url.endsWith("ckUserIsLogin")){
			return true;
		}else{
			String userCookie = CookieUtils.getUserCookie(request,Dict.USER_LOGIN_COOKIE);
			
			if(CommonUtils.getCurrentUserId(request) == null) {
				response.sendRedirect("./login.html");
			}
			if(CommonUtils.isNotEmpty(userCookie) && redisIsEnabled) {
				Boolean isLogin = redisUtils.hasKey(userCookie);
				if(isLogin) {
					//用户已登录
					String userInfo = redisUtils.getString(userCookie);
					redisUtils.setString(userCookie, userInfo, timout);
					
					//判断是否支持同步登录
					if("0".equals(userConfigService.ckUserSync(request))) {
						//与redis中的cookieid进行比较
						User user = JSON.parseObject(userInfo, User.class);
						String cookieId = redisUtils.getString(user.getId());//获取最新的cookieid
						if(userCookie.equals(cookieId)) {
							redisUtils.setString(user.getId(), cookieId,timout);
							
							//检查session中userid是否失效
							if(CommonUtils.getCurrentUserId(request) == null) {
								HttpSession session = request.getSession();
								session.setAttribute(Dict.SESSION_USERID, user.getId());
							}
							return true;
						}else {
							//跳转登录页面
							response.sendRedirect("./login.html");
						}
					}
				}
			}
		}
		return true;
	}
	

	/**
	 * 保存cookie案例
	 * @param response
	 * @param request
	 */
	private void saveCookie(HttpServletResponse response,HttpServletRequest request) {
		//设置输出编码格式
		response.setCharacterEncoding("UTF-8");
		
		//客户端以utf-8方式接受
		response.setContentType("text/html;charset=UTF-8");
		
		//获取cookies数组
		Cookie[] cookies = request.getCookies();
		
		if(CommonUtils.isNotEmpty(cookies)) {
			for (Cookie cookie : cookies) {
				if("lastRequestTime".equals(cookie.getName())) {
					System.out.println("-------------您上次访问的时间是：" + cookie.getValue());
					cookie.setValue(CommonUtils.getDateTime());
				}
				
			}
		}else {
			System.out.println("-----------第一次访问--------------------");
		}
		Cookie cookie = new Cookie("lastRequestTime", CommonUtils.getDateTime());
		response.addCookie(cookie);
		
	}

}
